<template>
  <div class="AdministratorCompanyList" id="AdministratorCompanyList">
    <cus-Breadcrumb level1="企业管理页面" level2="企业成员管理  " class="mb20"></cus-Breadcrumb>
    <!-- <el-tag>当前企业:</el-tag> -->
    <div class="btnBox">
      <el-button @click="addNumber=true;" class="addNumber">新增企业成员</el-button>
      <el-button @click="AaddNumber=true;" class="addNumber">批量上传</el-button>
      <el-button @click="returnBack()" class="addNumber">返回上一层</el-button>
      <el-input
        class="usernameSearch"
        v-model="name"
        @blur="flipList(value4)"
        @keyup.enter.native="flipList(value4)"
        placeholder="按姓名快捷查询企业成员，回车触发"
      ></el-input>
    </div>
    <el-switch
      style="display: block"
      v-model="value4"
      active-color="#13ce66"
      inactive-color="#ff4949"
      active-text="查询当前公司下所有成员"
      inactive-text="只查询当前公司下成员"
      @change="changeStateToSearchCompanyNumber"
    ></el-switch>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="userName" label="姓名" width="180"></el-table-column>
      <el-table-column prop="phone" label="手机号" width="180"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          <el-button size="mini" type="primary" @click="addManager(scope.$index, scope.row)">设为管理员</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="批量新增"
      :visible.sync="AaddNumber"
      v-dialogDrag
      :close-on-click-modal="false"
      :modal="false"
    >
      <el-upload
        class="upload-demo"
        drag
        action="https://jsonplaceholder.typicode.com/posts/"
        multiple
        :before-upload="beforeUpdata"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">只能上传Excel文件</div>
      </el-upload>
    </el-dialog>

    <el-dialog
      title="新增企业人员"
      :visible.sync="addNumber"
      v-dialogDrag
      :close-on-click-modal="false"
      :modal="false"
    >
      <div class="addFormBox">
        <el-form ref="form" :model="addForm" label-width="80px">
          <el-form-item label="姓名">
            <el-input v-model="addForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="手机" label-width="80px">
            <el-input v-model="addForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="工号" label-width="80px">
            <el-input v-model="addForm.staffNum"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" type="primary" @click="handleAdd()">新增</el-button>
            <el-button size="mini" type="primary" @click="cancelAdd()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog
      title="修改企业人员"
      :visible.sync="editNumber"
      v-dialogDrag
      :close-on-click-modal="false"
      :modal="false"
    >
      <div class="editFormBox">
        <el-form ref="form" :model="editForm" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="editForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="手机" label-width="80px">
            <el-input v-model="editForm.phone"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" type="primary" @click="edit()">提交</el-button>
            <el-button size="mini" type="primary" @click="cancelEdit()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog
      title="新增用户"
      :visible.sync="addNumberFlag"
      v-dialogDrag
      :close-on-click-modal="false"
      :modal="false"
    >
      <div class="editFormBox">
        <el-form ref="form" :model="newManager" label-width="80px">
          <el-form-item label="登录名">
            <el-input v-model="newManager.loginName"></el-input>
          </el-form-item>
          <el-form-item label="密码" label-width="80px">
            <el-input v-model="newManager.password1"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" label-width="80px">
            <el-input v-model="newManager.password2"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="mini" type="primary" @click="commit()">提交</el-button>
            <el-button size="mini" type="primary" @click="cancelCommit()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <div class="pagination">
      <el-pagination
        :page-size="10"
        :pager-count="11"
        layout="total, prev, pager, next"
        :total="total"
        :page-sizes="[10]"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
</template>
<script>
import $$ from '@/plugins/statusCode.config'
export default {
  data () {
    return {
      addNumberFlag: false,
      total: 0,
      editForm: {
        userName: '',
        phone: '',
        id: ''
      },
      value4: false,
      tableData: [],
      dipartmentName: JSON.parse(sessionStorage.getItem('dipartmentName')),
      AaddNumber: false,
      addNumber: false,
      editNumber: false,
      addForm: {
        departmentId: '',
        departmentCode: '',
        userName: '',
        phone: '',
        staffNum: ''
      },
      newManager: {
        phone: '',
        userName: '',
        loginName: '',
        nickName: '',
        password1: '',
        password2: '',
        roleName: '',
        roleId: '',
        departmentName: '',
        departmentId: '',
        departmentCode: ''
      },
      name: '',
      pageNo: 1
    }
  },
  mounted () {
    this.flipList(this.value4)
    this.role()
  },
  created () {
  },
  beforeCreate () {},
  methods: {
    role () {
      let arr = JSON.parse(sessionStorage.getItem('buttonRole'))
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] === 'tkxt-search') {
          this.tkxtSearch = true
        }
        if (arr[i] === 'tkxt-edit') {
          this.tkxtEdit = true
        }
        if (arr[i] === 'tkxt-delete') {
          this.tkxtDelete = true
        }
      }
    },
    commit () {
      if (
        this.newManager.password1 &&
        this.newManager.password2 &&
        this.newManager.loginName
      ) {
        if (this.newManager.password1 === this.newManager.password2) {
          const that = this
          let param = new URLSearchParams()
          param.append('nickName', '')
          param.append('userName', this.newManager.userName)
          param.append('loginName', this.newManager.loginName)
          param.append('departmentName', this.newManager.departmentName)
          param.append('departmentId', this.newManager.departmentId)
          param.append('departmentCode', this.newManager.departmentCode)
          param.append('password', this.newManager.password1)
          param.append('phone', this.newManager.phone)
          param.append('roleName', '')
          param.append('roleId', '')
          this.$http8080
            .post('/manager-operate/save', param)
            .then(function (res) {
              if (res.data.statusCode === $$.s20000) {
                that.addNumberFlag = false
                that
                  .$confirm(
                    '管理员设置成功，是否前往配置用户角色',
                    '温馨提示',
                    {
                      confirmButtonText: '确定',
                      cancelButtonText: '取消',
                      type: 'warning'
                    }
                  )
                  .then(() => {
                    that.$router.push({ name: 'PersonnelAndManagement' })
                  })
                  .catch(() => {
                    that.$message({
                      type: 'info',
                      message: '已取消跳转'
                    })
                  })
              } else {
                that.addNumberFlag = false
                that.$message.error(res.data.statusMsg)
              }
            })
        } else {
          this.$message.error('两次填写密码不一样')
        }
      } else {
        this.$message.error('请检查是否填写完整')
      }
    },
    // 新增管理员
    addManager (index, row) {
      this.newManager.departmentName = sessionStorage.getItem(
        'AddDepartmentName'
      )
      this.newManager.departmentCode = row.departmentCode
      this.newManager.userName = row.userName
      this.newManager.departmentId = row.departmentId
      this.newManager.departmentId = row.departmentId
      this.newManager.phone = row.phone
      this.addNumberFlag = true
    },
    // 渲染列表
    handleCurrentChange (val) {
      this.pageNo = val
      this.flipList(this.value4)
    },
    async flipList (flag) {
      this.addForm = JSON.parse(sessionStorage.getItem('addForm'))
      let param = new URLSearchParams()
      param.append('departmentId', flag ? '' : this.addForm.departmentId)
      param.append('departmentCode', !flag ? '' : this.addForm.departmentCode)
      param.append('userName', this.name || '')
      param.append('pageNo', this.pageNo)
      param.append('pageSize', 10)
      const that = this
      await this.$http8081
        .post(`/department-staff-search/flipList`, param)
        .then(function (res) {
          if (res.data.statusCode === $$.s20006) {
            that.$message.success('查询企业成员列表成功')
            that.tableData = res.data.data.records
            that.total = res.data.data.total
          } else {
            that.$message.error(res.data.statusMsg)
          }
        })
    },
    changeStateToSearchCompanyNumber () {
      this.flipList(this.value4)
    },
    // 删除
    async handleDelete (index, row) {
      const rows = row
      let param = new URLSearchParams()
      param.append('id', rows.id)
      const that = this
      await this.$http8080
        .post(`/department-staff-operate/removeDepartmentStaffById`, param)
        .then(function (res) {
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  // 更新成功
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  that.searchChildCategory(null, rows)
                }
                if (res.data.statusCode === $$.s70003) {
                  sessionStorage.clear()
                  that.$router.push({ name: 'login' })
                  that.$message.success('登陆超时请重新登陆')
                }
              })
          }
          if (res.data.statusCode === $$.s20004) {
            that.flipList(that.value4)
          } else {
            that.$message.error(res.data.statusMsg)
          }
        })
    },
    // 增加
    async handleAdd () {
      const that = this
      let param = new URLSearchParams()
      param.append('departmentId', this.addForm.departmentId)
      param.append('departmentCode', this.addForm.departmentCode)
      param.append('userName', this.addForm.userName)
      param.append('phone', this.addForm.phone)
      param.append('pageNo', 1)
      param.append('pageSize', 30)
      await this.$http8080
        .post(`/department-staff-operate/saveDepartmentStaff`, param)
        .then(function (res) {
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  // 更新成功
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  that.handleAdd()
                }
                if (res.data.statusCode === $$.s70003) {
                  sessionStorage.clear()
                  that.$router.push({ name: 'login' })
                  that.$message.success('登陆超时请重新登陆')
                }
              })
          }
          if (res.data.statusCode === $$.s20000) {
            that.$message.success('添加企业成员成功')
            that.addNumber = false
            that.flipList(that.value4)
          } else {
            that.$message.error(res.data.statusMsg)
          }
        })
    },
    async beforeUpdata (file) {
      const files = file
      let fd = new FormData()
      fd.append('file', files)
      fd.append('departmentId', this.addForm.departmentId)
      fd.append('departmentCode', this.addForm.departmentCode)
      const that = this
      await this.$http8080
        .post('/department-staff-operate/saveDepartmentStaffFromExcel', fd)
        .then(function (res) {
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  // 更新成功
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  that.beforeUpdata(files)
                }
                if (res.data.statusCode === $$.s70003) {
                  sessionStorage.clear()
                  that.$router.push({ name: 'login' })
                  that.$message.success('登陆超时请重新登陆')
                }
              })
          }
          if (res.data.statusCode === $$.s20000) {
            that.AaddNumber = false
            that.$message.success(res.data.statusMsg)
            that.flipList(that.value4)
          } else {
            that.$message.error(res.data.statusMsg)
          }
        })
    },
    handleEdit (index, row) {
      this.editNumber = true
      this.editForm.userName = row.userName
      this.editForm.phone = row.phone
      this.editForm.id = row.id
    },
    async edit () {
      const that = this
      let param = new URLSearchParams()
      param.append('userName', this.editForm.userName)
      param.append('phone', this.editForm.phone)
      param.append('id', this.editForm.id)
      await this.$http8080
        .post(`/department-staff-operate/modifyDepartmentStaff`, param)
        .then(function (res) {
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  // 更新成功
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  that.edit()
                }
                if (res.data.statusCode === $$.s70003) {
                  sessionStorage.clear()
                  that.$router.push({ name: 'login' })
                  that.$message.success('登陆超时请重新登陆')
                }
              })
          }
          if (res.data.statusCode === $$.s20002) {
            that.editNumber = false
            that.flipList(that.value4)
            that.$message.success(res.data.statusCode)
          } else {
            that.$message.error(res.data.statusCode)
          }
        })
    },
    cancelAdd () {
      this.addForm.departmentId = ''
      this.addForm.departmentCode = ''
      this.addForm.userName = ''
      this.addForm.phone = ''
      this.addForm.staffNum = ''
      this.addNumber = false
    },
    cancelEdit () {
      this.editForm.userName = ''
      this.editForm.phone = ''
      this.editForm.id = ''
      this.editNumber = false
    },
    returnBack () {
      this.$router.push({ name: 'HandleEnterpriseList' })
    }
  }
}
</script>
<style scope="scoped">
#AdministratorCompanyList .btnBox {
  margin-bottom: 15px;
}
.AdministratorCompanyList .el-switch {
  margin-bottom: 15px;
}
#AdministratorCompanyList .usernameSearch {
  width: 300px;
}
#AdministratorCompanyList .addNumber {
  margin-right: 10px;
}
#AdministratorCompanyList .pagination {
  position: absolute;
  right: 120px;
  top: 120px;
}
</style>
